package cn.cheln.explorer.ds.scan;

import java.io.File;
import java.util.Map;
import java.util.TreeMap;

import android.content.Context;
import android.content.Intent;
import android.os.HandlerThread;
import android.os.Process;
import android.view.View;
import android.widget.Toast;
import cn.cheln.explorer.beans.FileUtil;
import cn.cheln.explorer.beans.UpdateBean;
import cn.cheln.explorer.config.Config;
import cn.cheln.explorer.config.Constants;
import cn.cheln.explorer.ds.sdcard.TypeFilter;
import cn.cheln.explorer.ds.uri.NavigationConstants;
import cn.cheln.explorer.ds.util.FileMgrCategory;
import cn.cheln.support.images.MimeUtil;
import cn.cheln.support.log.Logs;
import cn.cheln.support.mobile.sdcard.SDcardChecker;
import cn.cheln.support.unknown.ComparatorRepo;
import cn.power.shine.R;

import com.direction.hold.ui.CountActivity;

public class Scanner extends cn.cheln.explorer.ds.sdcard.TypeFilter implements
		java.io.FileFilter {

	private MirrManager dataSychroInMemory;
	Context context;
	Map<String, String> oftenUsedType = new TreeMap<String, String>(
			ComparatorRepo.stringKey);
	String type;
	int i = 0;

	public Scanner(MirrManager dataSychroInMemory, Context context,
			Integer[] filter_mode, TypeFilter.TextWrapper[] exclude,
			String[] includeExamples, String type) {
		super(filter_mode, exclude, includeExamples);
		this.context = context;
		this.type = type;
		this.dataSychroInMemory = dataSychroInMemory;
		dataSychroInMemory.receiveDBImage(context, type);
		if (type == null || type.equals(Constants.CateContants.CATE_IMAGES)) {
			oftenUsedType.put("jpg", "image");
			oftenUsedType.put("jpeg", "image");
			oftenUsedType.put("bmp", "image");
			oftenUsedType.put("gif", "image");
			oftenUsedType.put("png", "image");
			oftenUsedType.put("webp", "image");
		}
		if (type == null || type.equals(Constants.CateContants.CATE_MUSIC)) {
			oftenUsedType.put("mp3", "audio");
			oftenUsedType.put("wav", "audio");
			oftenUsedType.put("amr", "audio");
		}
		if (type == null || type.equals(Constants.CateContants.CATE_VIDEO)) {
			oftenUsedType.put("avi", "video");
			oftenUsedType.put("wmv", "video");
			oftenUsedType.put("mpg", "video");
			oftenUsedType.put("3gp", "video");
			oftenUsedType.put("mp4", "video");
			oftenUsedType.put("mkv", "video");
			oftenUsedType.put("webm", "video");
			oftenUsedType.put("m4v", "video");
			oftenUsedType.put("mov", "video");
		}
		if (type == null || type.equals(Constants.CateContants.CATE_DOCS)) {
			oftenUsedType.put("doc", "doc");
			oftenUsedType.put("docx", "doc");
			oftenUsedType.put("xls", "doc");
			oftenUsedType.put("xlsx", "doc");
			oftenUsedType.put("ppt", "doc");
			oftenUsedType.put("pptx", "doc");
			oftenUsedType.put("htm", "doc");
			oftenUsedType.put("html", "doc");
			oftenUsedType.put("txt", "doc");
			oftenUsedType.put("rtx", "doc");
			oftenUsedType.put("rtf", "doc");
			oftenUsedType.put("zip", "doc");
			oftenUsedType.put("csv", "doc");
			oftenUsedType.put("rar", "doc");
			oftenUsedType.put("pdf", "doc");

		}
		if (type == null || type.equals(Constants.CateContants.CATE_PACKAGE)) {
			oftenUsedType.put("apk", "apk");
		}
		if (type == null || type.equals(Constants.CateContants.CATE_THEME)) {
			oftenUsedType.put("lwt", "lewa/theme");
		}

	}

	String catename;
	String ext;

	@Override
	public boolean accept(File file) {
		// TODO Auto-generated method stub
		if (!super.accept(file)) {
			return false;
		}
		catename = "";
		ext = "";
		if (file.isDirectory()) {
			catename = Constants.CateContants.CATE_FOLDER;
		} else {
			ext = FileUtil.getRealLowerCaseExtension(file.getName());
			if (ext.length() == 0) {
				return false;
			}
			catename = oftenUsedType.get(ext);

			if (catename == null) {
				catename = FileMgrCategory.getCategory(MimeUtil
						.parseWholeMime(ext));
			}
			if (catename == null || catename.trim().equals("")
			// || (Config.is4_0Lower && FileMgrCategory.mediaCategory
			// .contains(catename))
					|| (type != null && !catename.equals(type))) {
				return false;
			}
		}
		UpdateBean ubFromDB = null;
		boolean equals = false;
		MirrDetail fimage = null;
		UpdateBean ubonDisk = null;
		try {
			fimage = dataSychroInMemory.getMemoryImage().get(catename);

			if (fimage == null) {
				// Logs.d("=== catename "+catename);
				// Logs.d("=== fimage "+fimage);

				// Logs.d("=== file.getAbsolutePath() "+file.getAbsolutePath());
			}
			// if (file.isFile()) {
			ubonDisk = new UpdateBean(null, file.getAbsolutePath(),
					String.valueOf(file.length()), String.valueOf(file
							.lastModified()), null, null);
			equals = (ubonDisk.equals(ubFromDB = fimage.records.get(file
					.getAbsolutePath())));

			// Logs.i("=============================");
			// Logs.i(" ubonDisk "+ubonDisk);
			// Logs.i(" ubFromDB "+ubFromDB+" ifExists "+ifExists);
			// }else{
			// ifExists = true;
			// }

			if (SDcardChecker.srcardStateResolve()) {
				return false;
			}
			if (!equals) {
				Logs.i("", ubFromDB != null ? "update" : "insert");
				MirrManager.doDBSync(file, fimage.operUri, context,
						ubFromDB != null, ubFromDB, ext);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (!equals) {
			i++;
			if (i % 500 == 0) {
				Intent intent = new Intent(ScanUpdateReceiver.ACTION_RECEIVER_SCAN);
				context.sendBroadcast(intent);
				i = 0;
			}
		} 
			fimage.records.remove(file.getAbsolutePath());
			// Logs.i("=======", "remove Image" + file.getAbsolutePath());
		
		if (file.isDirectory()) {
			file.listFiles(this);
			return false;
		}
		return false;
	}

	static Thread scanThread;
	static boolean isRunning;
	static String runningScanCategory = "";

	public static void scan(final String scanCategory, final Context context) {
		String finishText;
		if (isRunning) {
			Toast.makeText(context,
					context.getString(R.string.scaning, runningScanCategory),
					Toast.LENGTH_SHORT).show();
			return;
		}
		try {
			runningScanCategory = CountActivity.categoryActivity.navTool.navEntity
					.peek().displayname;
			runningScanCategory = runningScanCategory == null ? ""
					: runningScanCategory;
		} catch (Exception e) {
			return;
		}
		String home = context.getString(R.string.home);
		CountActivity.categoryActivity.setScanBarHide(false);
		CountActivity.categoryActivity.hideScanBar(View.VISIBLE);
		if (!runningScanCategory.equals(home)
				&& !runningScanCategory.equals("")) {
			Toast.makeText(
					context,
					context.getString(R.string.scaning_toast,
							runningScanCategory), Toast.LENGTH_SHORT).show();
		}
		Logs.i("-------------->>" + runningScanCategory);
		if (runningScanCategory.equals(home)) {
			finishText = context.getString(R.string.scan_finish_all_toast);
		} else if (runningScanCategory.equals("")) {
			finishText = "";
		} else {
			finishText = context.getString(R.string.scan_finish_toast)
					+ runningScanCategory;
			Logs.i("-------------->> finishText" + finishText);
		}
		final String finalFinishText = finishText;
		Logs.i("-------------->> finalFinishText" + finalFinishText);
		scanThread = new HandlerThread("", Process.THREAD_PRIORITY_LOWEST) {

			@Override
			public void run() {
				scanCategory(scanCategory, context, finalFinishText);
				isRunning = false;
			}
		};
		scanThread.start();
		isRunning = true;
	}

	public static void scanCategory(String scanCategory, Context context,
			String toastFinish) {
		MirrManager dataSychroInMemory = new MirrManager();
		Scanner allFilter = new Scanner(dataSychroInMemory, context,
				new Integer[] { TypeFilter.FILTER_BOTH_DIR_FILE,
						Config.getHiddenOption(Config.ACCOUNT_HIDE_OPTION) },
				Constants.HIDDEN_EXCLUDED, null, scanCategory);
		File file = new File(NavigationConstants.SDCARD_PATH);
		file.listFiles(allFilter);
		dataSychroInMemory.clearNoUseData(context);
		Intent intent = new Intent(ScanUpdateReceiver.ACTION_RECEIVER_SCAN);
		Logs.i("", "-------------->>>" + scanCategory);
		if (scanCategory != null && !scanCategory.trim().equals("")) {
			intent.putExtra(ScanUpdateReceiver.SCAN_FINISHED_TOAST, toastFinish);
			// Toast.makeText(context, toastFinish, Toast.LENGTH_LONG).show();
		}
		intent.putExtra(ScanUpdateReceiver.SCAN_FINISHED, true);
		context.sendBroadcast(intent);
	}
}
